package com.cxl.demo;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketServer {



    public static void main(String[] args) throws Exception {
        // 主从  bossServer  workServer

        //
        ServerSocket serverSocket = new ServerSocket(9000);
        while (true){
            Socket  socket = serverSocket.accept();// 阻塞 等待连接
            new WorkerSocket(socket).start();
        }
//        serverSocket.close();
    }

    static class WorkerSocket extends  Thread{
        Socket socket;

        public WorkerSocket(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try {
                InputStream in  = socket.getInputStream();
                InputStreamReader reader= new InputStreamReader(in);
                OutputStream outputStream =socket.getOutputStream();
                char[] chars =  new char[1024];
                int len = reader.read(chars);

                if (len!=-1){
                    String str = new String(chars,0,len);
                    System.out.println(Thread.currentThread().getName()+"服务端收到信息 : " + str);
                    outputStream.write("收到信息".getBytes());
                }
                // test upload
                // 关闭
                outputStream.close();
                in.close();
                reader.close();
                socket.close();
            }catch (Exception e){
                e.printStackTrace();
            }

        }
    }
}
